import React, { useState, useEffect,useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  Alert,
  TouchableOpacity,
  Image,
  ScrollView,
  Modal,
  Platform,
  FlatList
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { launchImageLibrary } from 'react-native-image-picker';
import DateTimePicker from '@react-native-community/datetimepicker';
import Icon from 'react-native-vector-icons/FontAwesome';
import { useNavigation } from '@react-navigation/native';

const ProfileEdit = () => { 
  const [isEditing, setIsEditing] = useState(false);
  const [username, setUsername] = useState('');
  const [bio, setBio] = useState('');
  const [gender, setGender] = useState('');
  const [birthday, setBirthday] = useState('');
  const [phone, setPhone] = useState('');
  const [avatar, setAvatar] = useState(null);
  const [showDatePicker, setShowDatePicker] = useState(false);
  const [showGenderPicker, setShowGenderPicker] = useState(false);
  const [tempDate, setTempDate] = useState(new Date());
  const navigation = useNavigation();

  const genderOptions = [
    { label: '男', value: 'male' },
    { label: '女', value: 'female' },
    { label: '其他', value: 'other' }
  ];

  useEffect(() => {
    const fetchProfile = async () => {
      try {
        const token = await AsyncStorage.getItem('authToken');
        const response = await fetch('http://124.222.104.145:8003/user/profile/', {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        });
        const data = await response.json();
        setUsername(data.username || '');
        setBio(data.bio || '');
        setGender(data.gender || '');
        setBirthday(data.birthday || '');
        if (data.birthday) {
          setTempDate(new Date(data.birthday));
        }
        setPhone(data.phone || '');
        if (data.profile_picture) {
          setAvatar({ uri: `http://124.222.104.145:8003${data.profile_picture}` });
        }
      } catch (error) {
        console.error('获取个人资料失败:', error);
      }
    };
    fetchProfile();
  }, []);

  const handleChoosePhoto = () => {
    const options = {
      mediaType: 'photo',
      quality: 1,
    };

    launchImageLibrary(options, async (response) => {
      if (response.didCancel) {
        return;
      }

      if (response.errorCode) {
        Alert.alert('错误', '选择图片时出错');
        return;
      }

      if (response.assets && response.assets[0]) {
        const selectedImage = response.assets[0];
        setAvatar({ uri: selectedImage.uri });

        // 立即上传头像
        await uploadAvatar(selectedImage);
      }
    });
  };

  const handleDateChange = (event, selectedDate) => {
    setShowDatePicker(false);
    if (selectedDate) {
      setTempDate(selectedDate);
      setBirthday(selectedDate.toISOString().split('T')[0]);
    }
  };

  const handleSave = async () => {  
    try {
      const token = await AsyncStorage.getItem('authToken');

      // 准备要更新的数据
      const updateData = {
        nickname: username || '',
        bio: bio || '',
        gender: gender || '',
        birthday: birthday || '',
        phone: phone || ''
      };

      console.log('Updating profile with data:', updateData);

      const response = await fetch('http://124.222.104.145:8003/user/profile/update/', {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(updateData)
      });

      console.log('Response status:', response.status);
      const responseData = await response.json();
      console.log('Response data:', responseData);

      if (response.ok) {
        Alert.alert('成功', '个人资料更新成功');
        setIsEditing(false);
      } else {
        let errorMessage = '更新失败';
        if (responseData.error) {
          if (typeof responseData.error === 'object') {
            // 如果错误是对象，提取所有错误消息
            errorMessage = Object.entries(responseData.error)
              .map(([field, errors]) => {
                if (Array.isArray(errors)) {
                  return `${field}: ${errors.join(', ')}`;
                }
                return `${field}: ${errors}`;
              })
              .join('\n');
          } else {
            errorMessage = responseData.error;
          }
        } else if (responseData.message) {
          errorMessage = responseData.message;
        }
        Alert.alert('错误', errorMessage);
      }
    } catch (error) {
      console.error('更新个人资料失败:', error);
      Alert.alert('错误', '更新失败，请检查网络连接');
    }
  };

  const renderInfoItem = (label, value) => {
    let displayValue = value;
    if (label === '性别') {
      switch (value) {
        case 'male':
          displayValue = '男';
          break;
        case 'female':
          displayValue = '女';
          break;
        case 'other':
          displayValue = '其他';
          break;
      }
    }
    return (
      <View style={styles.infoItem}>
        <Text style={styles.label}>{label}</Text>
        <Text style={[styles.info, !value && styles.unsetInfo]}>
          {displayValue || '未设置'}
        </Text>
      </View>
    );
  };

  const renderGenderItem = ({ item }) => (
    <TouchableOpacity
      style={[
        styles.genderItem,
        gender === item.value && styles.genderItemTextSelected
      ]}
      onPress={() => {
        setGender(item.value);
        setShowGenderPicker(false);
      }}
    >
      <Text style={[
        styles.genderItemText,
        gender === item.value && styles.genderItemTextSelected
      ]}>
        {item.label}
      </Text>
    </TouchableOpacity>
  );

  const uploadAvatar = async (imageFile) => {
    try {
      const token = await AsyncStorage.getItem('authToken');
      const formData = new FormData();

      // 修改文件对象的结构
      const file = {
        uri: Platform.OS === 'android' ? imageFile.uri : imageFile.uri.replace('file://', ''),
        type: imageFile.type || 'image/jpeg',
        name: imageFile.fileName || 'photo.jpg',
      };

      formData.append('profile_picture', file);

      console.log('Uploading file:', file); // 调试日志

      const response = await fetch('http://124.222.104.145:8003/user/profile/update/', {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json',
          // 注意：使用 FormData 时不要手动设置 Content-Type，让它自动设置
        },
        body: formData,
      });

      console.log('Response status:', response.status); // 调试日志
      const responseData = await response.json();
      console.log('Response data:', responseData); // 调试日志

      if (response.ok) {
        Alert.alert('成功', '头像更新成功');
      } else {
        Alert.alert('错误', `头像更新失败: ${responseData.message || responseData.error || '请重试'}`);
      }
    } catch (error) {
      console.error('上传头像失败:', error);
      Alert.alert('错误', '上传头像失败，请检查网络连接');
    }
  };

  return (
    <ScrollView style={styles.container} showsVerticalScrollIndicator={false}>
      {/* 顶部栏 */}
      <View style={styles.header}>
                <TouchableOpacity onPress={() => navigation.goBack()}>
                    <Icon name="angle-left" size={28} color="#333" />
                </TouchableOpacity>
                <Text style={styles.headerTitle}>个人资料</Text>
                <View style={{ width: 28 }} />
      </View>

      <TouchableOpacity style={styles.avatarContainer} onPress={handleChoosePhoto}>
        <Image
          source={avatar || require('../assets/default_avatar.png')}
          style={styles.avatar}
        />
        <Text style={styles.changeAvatarText}>点击更换头像</Text>
      </TouchableOpacity>
      {!isEditing ? (
        <View>
          {renderInfoItem('用户名', username)}
          {renderInfoItem('简介', bio)}
          {renderInfoItem('性别', gender)}
          {renderInfoItem('生日', birthday)}
          {renderInfoItem('电话号码', phone)}
          <TouchableOpacity style={styles.editButton} onPress={() => setIsEditing(true)}>
            <Text style={styles.editButtonText}>修改资料</Text>
          </TouchableOpacity>
        </View>
      ) : (
        <View>
          <Text style={styles.label}>用户名</Text>
          <TextInput
            style={styles.input}
            placeholder="请输入用户名"
            value={username}
            onChangeText={setUsername}
          />
          <Text style={styles.label}>简介</Text>
          <TextInput
            style={styles.input}
            placeholder="请输入简介"
            value={bio}
            onChangeText={setBio}
            multiline
          />
          <Text style={styles.label}>性别</Text>
          <TouchableOpacity
            style={styles.pickerButton}
            onPress={() => setShowGenderPicker(true)}
          >
            <Text style={gender ? styles.pickerButtonText : styles.pickerPlaceholder}>
              {gender || '请选择性别'}
            </Text>
          </TouchableOpacity>

          <Text style={styles.label}>生日</Text>
          <TouchableOpacity
            style={styles.pickerButton}
            onPress={() => setShowDatePicker(true)}
          >
            <Text style={birthday ? styles.pickerButtonText : styles.pickerPlaceholder}>
              {birthday || '请选择生日'}
            </Text>
          </TouchableOpacity>

          <Text style={styles.label}>电话号码</Text>
          <TextInput
            style={styles.input}
            placeholder="请输入电话号码"
            value={phone}
            onChangeText={setPhone}
            keyboardType="phone-pad"
          />
          <TouchableOpacity style={styles.saveButton} onPress={handleSave}>
            <Text style={styles.saveButtonText}>保存</Text>
          </TouchableOpacity>
        </View>
      )}

      {/* 替换原来的性别选择器模态框 */}
      <Modal
        visible={showGenderPicker}
        transparent={true}
        animationType="fade"
        onRequestClose={() => setShowGenderPicker(false)}
      >
        <TouchableOpacity
          style={styles.modalOverlay}
          activeOpacity={1}
          onPress={() => setShowGenderPicker(false)}
        >
          <View style={styles.genderPickerContainer}>
            <Text style={styles.genderPickerTitle}>选择性别</Text>
            <FlatList
              data={genderOptions}
              renderItem={renderGenderItem}
              keyExtractor={item => item.value}
              style={styles.genderList}
            />
          </View>
        </TouchableOpacity>
      </Modal>

      {/* 日期选择器 */}
      {showDatePicker && (
        <DateTimePicker
          value={tempDate}
          mode="date"
          display={Platform.OS === 'ios' ? 'spinner' : 'default'}
          onChange={handleDateChange}
          maximumDate={new Date()}
        />
      )}
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 15,
        paddingTop: 40,
        paddingBottom: 10,
        backgroundColor: '#fff',
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
        justifyContent: 'space-between',
    },
  headerTitle: { fontSize: 20, fontWeight: 'bold', color: '#333' },
  avatarContainer: {
    alignItems: 'center',
    marginBottom: 20,
  },
  avatar: {
    width: 120,
    height: 120,
    borderRadius: 60,
    marginBottom: 10,
    borderWidth: 3,
    borderColor: '#fff',
  },
  changeAvatarText: {
    color: '#4CAF50',
    fontSize: 16,
    fontWeight: '500',
  },
  infoItem: {
    marginHorizontal: 20,
    marginBottom: 15,
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 15,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  label: {
    fontSize: 14,
    color: '#666',
    marginBottom: 5,
    marginLeft: 20,
  },
  info: {
    fontSize: 16,
    color: '#333',
  },
  unsetInfo: {
    color: '#999',
    fontStyle: 'italic',
  },
  input: {
    marginHorizontal: 20,
    marginBottom: 15,
    padding: 12,
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    backgroundColor: '#fff',
    fontSize: 16,
  },
  pickerButton: {
    marginHorizontal: 20,
    marginBottom: 15,
    padding: 12,
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    backgroundColor: '#fff',
  },
  pickerButtonText: {
    fontSize: 16,
    color: '#333',
  },
  pickerPlaceholder: {
    fontSize: 16,
    color: '#999',
  },
  editButton: {
    margin: 20,
    padding: 12,
    backgroundColor: '#4CAF50',
    borderRadius: 8,
    alignItems: 'center',
  },
  editButtonText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
  saveButton: {
    margin: 20,
    padding: 12,
    backgroundColor: '#4CAF50',
    borderRadius: 8,
    alignItems: 'center',
  },
  saveButtonText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  genderPickerContainer: {
    width: '80%',
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 20,
    elevation: 5,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 4,
  },
  genderPickerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
    textAlign: 'center',
    marginBottom: 15,
  },
  genderList: {
    maxHeight: 200,
  },
  genderItem: {
    paddingVertical: 12,
    paddingHorizontal: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  genderItemText: {
    fontSize: 16,
    color: '#333',
    textAlign: 'center',
  },
  genderItemTextSelected: {
    color: '#4CAF50',
    fontWeight: '600',
  },
});

export default ProfileEdit;